package com.yuandian.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 说明：码工具类
 * @Author zfsn
 * @Date 2022/10/18 17:42
 */
@Slf4j
public final class CodeUtil {

    /**
     * md5打编码，100w次调用，单线程测试：1047ms，10个线程测试：814ms
     * @param text 待编码的文本
     * @return 编码
     */
    public static String md5(String text) {
        if (StringUtils.isEmpty(text)) {
            return "0000000000000000";
        }
        return DigestUtils.md5DigestAsHex(text.getBytes()).substring(8, 24);
    }

    /**
     * 解码base64
     * @param text base64字符串
     * @return 解码后的字符串
     */
    public static String decodeBase64(String text) {
        if (StringUtils.isEmpty(text)) {
            return text;
        }
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            return new String(decoder.decode(text.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
        } catch (IllegalArgumentException e) {
            log.error("base64解码失败，待解码字符串：{}", text);
        }
        return text;
    }

	public static String getCode(String number){
		String codeNum = "00000000";
		int codeNumLen=codeNum.length();
		int numLen=number.length();
		int n=codeNumLen-numLen;
		if(n <= 0){
			return number;
		}else{
			codeNum = codeNum.substring(0,n) + number;
		}
		return 	codeNum;
	}

    /**
     * 解码unicode
     * @param text unicode字符串
     * @return 解码后的字符串
     */
    public static String decodeUnicode(String text) {
        if (StringUtils.isEmpty(text)) {
            return text;
        }
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(text);
        char ch;
        while (matcher.find()) {
            String group = matcher.group(2);
            ch = (char) Integer.parseInt(group, 16);
            String group1 = matcher.group(1);
            text = text.replace(group1, ch + "");
        }
        return text;
    }

    /**
     * 解码url
     * @param text url字符串
     * @return 解码后的字符串
     */
    public static String decodeUrl(String text) {
        if (StringUtils.isEmpty(text)) {
            return text;
        }
        try {
            text = text.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            text = text.replaceAll("\\+", "%2B");
            return URLDecoder.decode(text, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            log.error("url解码异常", e);
        }
        return null;
    }
}
